package com.kezesong.leasing.controller;

import com.kezesong.leasing.common.ResponseResult;
import com.kezesong.leasing.common.enums.ReturnCodeEnum;
import com.kezesong.leasing.common.exception.CommonException;
import com.kezesong.leasing.controller.response.UserLoginRspBody;
import com.kezesong.leasing.controller.response.WeixinRspBody;
import com.kezesong.leasing.dto.SessionInfo;
import com.kezesong.leasing.entity.UserInfoEntity;
import com.kezesong.leasing.service.SessionService;
import com.kezesong.leasing.service.UserInfoService;
import com.kezesong.leasing.service.WeixinService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/page")
public class UserController extends BaseController {


    @Autowired
    UserInfoService userInfoService;

    @Autowired
    private WeixinService weixinService;

    @Autowired
    private SessionService sessionService;

    @GetMapping("/wxAppAutoLogin/{code}")
    @ApiOperation(value = "wxAppAutoLogin", notes = "微信小程序自动登陆")
    public ResponseResult<UserLoginRspBody> wxAppAutoLogin(@PathVariable String code, HttpServletResponse httpServletResponse){
        WeixinRspBody weixinInfo = userInfoService.getWeixinInfo(code);
        UserInfoEntity userInfo = userInfoService.getUserInfoByOpenId(weixinInfo.getOpenId());
        if (null != userInfo && StringUtils.isNotBlank(userInfo.getOpenId())){
            UserLoginRspBody loginRspBody = new UserLoginRspBody();
            loginRspBody.setMaskTelNo(userInfo.getTelNo());
            loginRspBody.setNickName(userInfo.getUserName());
            SessionInfo sessionInfo = new SessionInfo();
            BeanUtils.copyProperties(userInfo,sessionInfo);
            String sessionId = sessionService.createSession(sessionInfo); //创建登录态
            sessionService.writeWxLoginCookie(sessionId,httpServletResponse); //下发登陆cookie
            ResponseResult<UserLoginRspBody> responseResult = buildSucessResponse(loginRspBody);
            return responseResult;
        }else {
            userInfo = new UserInfoEntity();
            if (StringUtils.isBlank(weixinInfo.getOpenId())){
                return buildFailedResponse(ReturnCodeEnum.PARAM_EMPTY,"openId is null");
            }
            userInfo.setOpenId(weixinInfo.getOpenId());
            userInfo.setUnionId(weixinInfo.getUnionId());
            int row = userInfoService.addUserInfo(userInfo);
            if (row>0){
                userInfo = userInfoService.getUserInfoByOpenId(weixinInfo.getOpenId());
                SessionInfo sessionInfo = new SessionInfo();
                BeanUtils.copyProperties(userInfo,sessionInfo);

                String sessionId = sessionService.createSession(sessionInfo); //创建登录态
                sessionService.writeWxLoginCookie(sessionId,httpServletResponse); //下发登陆cookie

                UserLoginRspBody loginRspBody = new UserLoginRspBody();
                loginRspBody.setMaskTelNo(userInfo.getTelNo());
                loginRspBody.setNickName(userInfo.getUserName());
                ResponseResult<UserLoginRspBody> responseResult = buildSucessResponse(loginRspBody);
                return responseResult;
            }else {
                ResponseResult<UserLoginRspBody> responseResult = buildNoDataResponse();
                return responseResult;
            }
        }
    }



    @GetMapping("/getWxPhoneNumber/{encryptedData}/{iv}")
    @ApiOperation(value = "getWxPhoneNumber", notes = "微信小程序获获取手机号")
    public ResponseResult<String> getWechatPhoneNumber(@PathVariable("encryptedData") String encryptedData, @PathVariable("iv") String iv, HttpServletRequest httpServletRequest)  {
        try {
            String sessionTicket = sessionService.getWeixinSessionTicket(httpServletRequest);
            SessionInfo sessionInfo = sessionService.getSessionInfo(sessionTicket);
            String wxSessionKey = sessionInfo.getWxSessionKey();
            String phoneNumber = weixinService.decryptPhoneNumber(encryptedData, iv, wxSessionKey);
            if (StringUtils.isNotBlank(phoneNumber)) {
                sessionInfo.setTelNo(phoneNumber);
                sessionService.refreshSession(sessionInfo); //获取手机号后刷新登录态
                ResponseResult<String> responseResult = buildSucessResponse(phoneNumber);
                return responseResult;
            }else {
                ResponseResult<String> responseResult = buildNoDataResponse();
                return responseResult;
            }
        } catch (ExecutionException e) {
            return buildFailedResponse();
        } catch (CommonException e) {
           return buildFailedResponse(e);
        }
    }


    @GetMapping("/testGetWxPhoneNumber/test/{telNo}")
    @ApiOperation(value = "testGetWxPhoneNumber", notes = "测试")
    public ResponseResult<String> testGetWxPhoneNumber(@PathVariable("telNo") String telNo) {
        ResponseResult<String> responseResult = buildSucessResponse(telNo);
        return responseResult;
    }

}
